#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/7/28
# @USER    : Shengji He
# @File    : dicom2nifti.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from SegFlow.dicom_io import dcm_to_nifti_LEGACY


def main():
    exe_path = r'***'
    dicom_folder = r'***\CTDICOM'

    save_folder = r'***'
    save_name = 'CT'
    dcm_to_nifti_LEGACY(dicom_folder, save_folder, save_name, False, exe_path)

    """
    # Simpler method
    reader = sitk.ImageSeriesReader()
    seriesID = reader.GetGDCMSeriesIDs(ct_dicom_folder)[0]
    dicom_names = reader.GetGDCMSeriesFileNames(ct_dicom_folder, seriesID)
    reader.SetFileNames(dicom_names)
    image = reader.Execute()
    pixelSpacing = image.GetSpacing()

    ct_array = sitk.GetArrayFromImage(image).astype(np.float32)

    ct_image = sitk.GetImageFromArray(ct_array)
    ct_image.SetSpacing(pixelSpacing)
    ct_image.SetDirection(nii_direction)
    sitk.WriteImage(ct_image, save_name)
    """


def temp():
    import os
    import SimpleITK as sitk
    exe_path = r'dcm2niix.exe'

    data_folder = r'D:\heshengji\tools\dataset\fastPET-LD\train'
    ct_folders = os.path.join(data_folder, 'CT')
    save_folder = os.path.join(data_folder, 'CT_nii')
    for ct_folder in os.listdir(ct_folders):
        ct_dicom_folder = os.path.join(ct_folders, ct_folder)
        save_name = os.path.join(save_folder, f'{ct_folder}.nii.gz')

        reader = sitk.ImageSeriesReader()
        seriesID = reader.GetGDCMSeriesIDs(ct_dicom_folder)[0]
        dicom_names = reader.GetGDCMSeriesFileNames(ct_dicom_folder, seriesID)
        reader.SetFileNames(dicom_names)
        image = reader.Execute()
        # pixelSpacing = image.GetSpacing()
        #
        # ct_array = sitk.GetArrayFromImage(image).astype(np.float32)
        #
        # ct_image = sitk.GetImageFromArray(ct_array)
        # ct_image.SetSpacing(pixelSpacing)
        # ct_image.SetDirection(nii_direction)
        sitk.WriteImage(image, save_name)

    pass


if __name__ == '__main__':
    temp()
    # main()
    print('done')
